package clinet

import (
	"golang.org/x/net/websocket"
	"log"
	"sync"
	"time"
)

//获取客户端加锁
var clientLock sync.Mutex

var origin = "http://192.168.11.250:8000"
var url = "ws://192.168.11.250:8000"

type wsClient struct {
	Client *websocket.Conn
	Time   int64
}

//websocket 客户端公共变量
var (
	WsClient wsClient
)

//日志配置
func init() {
	log.SetFlags(log.Ldate | log.Lmicroseconds | log.Llongfile)
}

func IsNormalRun() bool {
	if WsClient.Client == nil {
		return false
	} else {
		return true
	}
}

func Connect(msg string) *websocket.Conn {
	clientLock.Lock()
	if WsClient.Client == nil {
		connectMsg := map[string]string{"msg": msg}
		for {
			log.Printf("连接信息：%s\n", connectMsg["msg"])
			ws, err := websocket.Dial(url, "", origin)
			if err != nil {
				log.Printf("连接失败：%s\n", err)
				time.Sleep(time.Second * 30)
				connectMsg["msg"] = "创建连接失败重新创建连接"
			} else {
				WsClient = wsClient{ws, time.Now().Unix() * 1000}
				log.Printf("客户端创建连接成功...............")
				break
			}
		}
	}
	clientLock.Unlock()
	return WsClient.Client
}
